<template>
  <div style="padding:15px">
    <div class="text-wrap flex flex-center flex-col-between">
      <div class="desc-text text-primary">
        <i class="el-icon-s-grid" />
        <span class="text">排程表格</span>
      </div>

      <div class="filter-container">
        <el-select class="filter-item" style="width: 260px;margin-left: 5px" v-model="query.ScheduleVersionId"
          placeholder="排程版本">
          <el-option v-for="i in VersionList" :key="i.value" :label="i.label" :value="i.value"></el-option>
        </el-select>
        <el-select class="filter-item" @change="research" clearable style="width: 360px;margin-left: 5px" v-model="query.GroupId"
          placeholder="选择工序">
          <el-option v-for="i in GroupList" :key="i.value" :label="i.label" :value="i.value"></el-option>
        </el-select>

        <!-- <el-button class="filter-item" v-if="selectRows.length" type="danger" plain @click="research">删除
        </el-button> -->
        <el-button class="filter-item" type="success" plain @click="research">查询
        </el-button>
        <el-button class="filter-item" v-if="selectRows.length" type="primary" :loading='taskLoading' plain
          @click="taskInsert">任务下发
        </el-button>
        <el-button class="filter-item" type="warning" v-if="updateFlag" plain @click="updateCalculate">重新计算
        </el-button>
        <el-button class="filter-item" type="primary" v-if="updateFlag" plain @click="saveData">保存排程
        </el-button>
      </div>

    </div>
    <n-config-provider :theme-overrides="themeOverrides">
      <n-data-table :bordered="false" :single-line="false" ref="table" :checked-row-keys='selectRows'
        @update:checked-row-keys="handleCheck" :columns="columns" :data="data" :max-height="550" :scroll-x="1800"
        virtual-scroll />
      <!-- <button @click="getData">获取data</button> -->
    </n-config-provider>

    <el-dialog :title="`${curDate} 生产信息`" width="70%" v-model="dialogVisible">
      <z-Table :list="curMachineList" :tableProps="tableProps" :columns="columnsMachine">
        <template v-slot:content="{ row, key }">
          <span v-if="key == 'StartTime'" v-timeFormat="row[key]" format="HH:mm"></span>
          <span v-else-if="key == 'EndTime'" v-timeFormat="row[key]" format="HH:mm"></span>
          <span v-else> {{ row[key] }}</span>
        </template>

      </z-Table>
    </el-dialog>
    <el-dialog :title="`${curMo?.MoCode} 出货日修改`" v-model="ChangeDeadLine">
      <el-date-picker v-model="changeDeadLineValue" type="date" placeholder="选择日期" />
      <div class="fr">
        <el-button type="info" @click="ChangeDeadLine = false">取消</el-button>
        <el-button type="primary" @click="HandeChangeDeadLine">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, h, getCurrentInstance } from "vue";
import { useDraggable } from 'vue-draggable-plus'
import { NButton, NTag, useMessage, NConfigProvider } from "naive-ui";
import dayjs from 'dayjs'
import _ from 'lodash'
import zTable from '../../_common/table.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  components: { zTable },
  data() {
    return {
      taskLoading: false,
      changeDeadLineValue: null,
      curDate: null,
      curMo: null,
      curMachineList: [],
      updateFlag:false,
      tableProps: {
        border: true,
        hideOperations: true,
      },
      CalculateTask:{},
      columnsMachine: [
        { title: '设备编码', key: 'MachineCode' },
        { title: '设备名称', key: 'MachineName' },
        // { title: '班次信息', key: 'ShiftType' },
        { title: '开始时间', key: 'StartTime' },
        { title: '结束时间', key: 'EndTime' },
        { title: '产出数量', key: 'Qty' },
        { title: '小时产能', key: 'UPH' },
        { title: '前置时长', key: 'BeforeMinutes' },
        { title: '准备时长', key: 'PreparationMinutes' },
        { title: '后置时长', key: 'AfterMinutes' },

      ],
      ChangeDeadLine: false,
      dialogVisible: false,
      themeOverrides: {},
      query: {},
      VersionList: [],
      GroupList: [],
      selectRows: [],
      data: [

      ],

      BasColumns: [
        {
          type: "selection",
          fixed: "left"
        },
        {
          title: "工序",
          key: "GroupCodeName",
          width: 120,
          fixed: "left"
        },
        {
          title: "工单",
          key: "MoCode",
          width: 120,
          fixed: "left",
          render: null,
        },
        {
          title: "产品",
          key: "ProductsCode",
          width: 120,
          fixed: "left"
        },
        {
          title: "数量",
          key: "Qty",
          width: 80,
          // fixed: "left"
        },
        {
          title: "UPH",
          key: "UPH",
          width: 80,
          // fixed: "left"
        },
        {
          title: "重量",
          key: "Weight",
          width: 80,
          // fixed: "left"
        },

        {
          title: "出货日",
          key: "DeadLine",
          width: 80,
          // fixed: "left",
          render: null,

        },
        // {
        //   title: "操作",
        //   key: "custom",
        //   width: 200,
        //   fixed: "right",
        //   render: null
        // }
      ],

      columns: [

      ],
    }


  },
  mounted() {
     this.initData()
    let DeadLine = this.BasColumns.find(i => i.key == 'DeadLine')
    DeadLine.render = this.ageRender;
    this.themeOverrides = {
      common: {
        primaryColor: '#7606E6'
      },
      Button: {
        textColor: '#7606E6'
      },
      Select: {
        peers: {
          InternalSelection: {
            textColor: '#7606E6'
          }
        }
      }
    }
  },

  methods: {

    taskInsert() {
      this.taskLoading = true
      let curSelect = this.data.filter(i => this.selectRows.includes(i.key))
      console.log(curSelect, 'curSelect')
      let data = curSelect.map(i => i.ScheduleTaskId)
      this.http.post('/api/Aps_ScheduleTask/SendTask', { ScheduleTaskIds: data }).then(r => {

      }).finally(i => {
        this.taskLoading = false

      })
    },

    titleRender(date, items) {
      return h("div", {
        style: 'color:orange',
        // onClick: (e) => this.handleTitleClick(date, items)
      }, date);
    },
    handleTitleClick(date, items) {
      this.curDate = date
      this.curMachineList = items
      this.dialogVisible = true
    },
    research() {
      let data = {
        ...this.query,
        GroupIds: [this.query.GroupId],
      }

      this.http.post('/api/Aps_ScheduleTask/GetGanttData', data).then(r => {
        this.renderData(r)
      })
    },
    saveData(){
      this.http.post('/api/Schedule/SaveSchedule', { ...this.CalculateTask }).then(r => {
        this.research()
        this.updateFlag = false

        thi.CalculateTask = {}
      })
    },
    updateCalculate(){

      this.http.post('/api/Schedule/HandSchedule', {MoList:this.data}).then(r => {
        this.renderData(r)
        this.CalculateTask = {
          reqTask:r.tasks,
          reqDate: r.taskDates
        }
      })
    },
    // 造数据
    renderData(r) {
      let that = this

      const { MinDate, MaxDate, task, taskDate } = r
      // 循环MinData到MaxData 时间
      let minDate = dayjs(MinDate)
      this.minDateStr = minDate.format('MM-DD')
      let maxDate = dayjs(MaxDate).add(1, 'day')
      this.columns = _.cloneDeep(this.BasColumns)
      this.data = task.map(i => {
        return {
          ...i,
          key: i.ScheduleTaskId
        }
      })

     
      // 循环时间，工单当天qty值多少显示在表格中
      for (let i = minDate; i.isBefore(maxDate); i = i.add(1, 'day')) {
        let date = i.format('MM-DD')
        this.data.forEach((j, index) => {
          let tmp = taskDate.find(x => x.MoCode == j.MoCode && dayjs(x.WorkDate).format('MM-DD') == date )
         
          if (!!tmp ) {

            //处理展示数据 找到对应的工序，工单，产品，给对应需要展示的数据塞入值
            if (tmp.GroupId == j.GroupId && tmp.MoCode == j.MoCode && tmp.ProductsCode == j.ProductsCode) {
              console.log(tmp,'Tmp')
              this.data[index][date] = tmp.Qty
              this.data[index]['detail'] = tmp.Details
            } else {
              this.data[index][date] = null
              this.data[index]['detail'] = []

            }
          } else {
            this.data[index][date] = null
            this.data[index]['detail'] = []

          }

          // 处理columns
          if(!this.columns.filter(i => i.curDate == date).length ) {
            this.columns.push({
              title: this.titleRender(date, this.data[index]['detail']),
              key: date,
              width: 80,
              curDate:date,
              render(row) {
                return h("div", {
                  style: 'color:green;cursor: pointer;font-weight:700',
                   onClick: (e) => that.handleTitleClick(date, tmp?.Details ?? [])
                }, row[date]);
              },
              fixed: false,
              only: true,
            })
          }
          

        })

      }
      this.columns.push({
        title: "操作",
        key: "custom",
        width: 100,
        fixed: "right",
        render: null
      })
      this.$nextTick(() => {
        // this.initSortable()
        console.log(this.data, 'data')
        console.log(this.columns, 'columns')
      })
    },
    initData() {
      this.http.post('/api/Aps_ScheduleVersion/GetPageData', { sort: "CreateTime" }).then(r => {
        this.VersionList = r.rows.map(i => {
          return {
            value: i.ScheduleVersionId,
            label: i.Version
          }
        })
        this.query.ScheduleVersionId = this.VersionList[0]?.value
        this.http.post('/api/Bas_GroupConfig/GetPageData', {order:'asc',sort:'GroupCode'}).then(r => {
          this.GroupList = r.rows.map(i => {
            return {
              value: i.GroupId,
              label: `${i.GroupCode} ${i.GroupName}`,
              code: `${i.GroupCode}`
            }
          })


        })
      })

    },
    handleCheck(items) {
      this.selectRows = [items[items.length-1]]
      let custom = this.columns.find(i => i.key == 'custom')
      if (items.length) {
        custom.render = this.customRender;
      } else {
        custom.render = null;
      }

    },
    ageRender(row, index) {
      return h("div", {
        style: 'color:red;cursor: pointer;',
       // onClick: (e) => this.handleAgeClick(row, index, e)
      }, dayjs(row.DeadLine).format('MM-DD'));
    },
    moveElements(ids, targetId) {
      const targetIndex = this.data.findIndex(item => item.key === targetId);

      const elementsToMove = [];
      ids.forEach(key => {
        const index = this.data.findIndex(item => item.key === key);
        if (index !== -1) {
          elementsToMove.push(this.data.splice(index, 1)[0]);
        }
      });

      elementsToMove.forEach(element => {
        this.data.splice(targetIndex + 1, 0, element);
      });
    },
    moveTop(row, index) {
      let curSelect = this.data.filter(i => this.selectRows.includes(i.key))
      this.data = this.data.filter(i => !this.selectRows.includes(i.key))
      let cIndex = this.data.findIndex(i => i.key == row.key)
      this.data.splice(cIndex, 0, ...curSelect)
      this.updateFlag = true
      this.selectRows = []
    },
    moveBottom(row, index) {
      let curSelect = this.data.filter(i => this.selectRows.includes(i.key))
      this.data = this.data.filter(i => !this.selectRows.includes(i.key))
      let cIndex = this.data.findIndex(i => i.key == row.key)
      this.data.splice(cIndex + 1, 0, ...curSelect)
      this.updateFlag = true
      this.selectRows = []
    
    },
    customRender(row, index) {
      if (!this.selectRows.length || this.selectRows.includes(row.key)) {
        return null
      }
      return h(
        'div',
        {},
        [
          h(
            NButton,
            {
              size: 'small',
              style: { marginRight: '10px' },
              onClick: () => this.moveTop(row, index),
            },
            { default: () => '向上' }
          ),
          h(
            NButton,
            {
              size: 'small',
              onClick: () => this.moveBottom(row, index),
            },
            { default: () => '向下' }
          ),
        ]
      );
    },
    HandeChangeDeadLine() {
      this.ChangeDeadLine = false
      // TODO 接口
      console.log("🚀 ~ HandeChangeDeadLine ~ this.curMo:", this.curMo)
    },
    handleAgeClick(row, index, e) {
      this.curMo = row
      this.changeDeadLineValue = row.DeadLine
      this.ChangeDeadLine = true
    },
    rowProps: (row, index, item) => {
      const { proxy } = getCurrentInstance();

      return {
        style: "cursor: pointer;",
        onClick: () => {
          proxy.$message.info(row)
        }
      };
    },
    initSortable: function () {
      // 获取表格row的父节点
      const ele = this.$refs.table.$refs.mainTableInstRef.$el.querySelector(".n-data-table-tbody")
      this.$nextTick(() => {
        useDraggable(ele, this.data)
      })
    },
    getData() {
      console.log("🚀 ~ getData ~ this.data:", this.data)
    },
  },
}
</script>

<style lang="scss">
.text-wrap {
  height: 40px;
  position: relative;
  padding-bottom: 8px;
  display: flex;

  .desc-text {
    //  display: inline-block;
    margin-top: 7px;
    font-weight: bold;
    //margin-bottom: 3px;
    font-size: 14px;
    white-space: nowrap;
    border-bottom: 2px solid #7300e6;

    i {
      font-size: 16px;
      position: relative;
      top: 1px;
      margin-right: 2px;
    }
  }
}
</style>
